﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;

namespace C_Chat.Funktions
{
    class Listerner
    {
        public bool Running;
        ChatForm form;
        RichTextBox box;
        Writing.Writer writer;
        private string StringData;

        public Listerner(ChatForm Form, RichTextBox Box)
        {
            form = Form;
            box = Box;
            writer = new Writing.Writer();
            Running = true;
        }

        public void run()
        {
            byte[] data;
            int recv = 0;

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, Configs.Broadcast.Port);
            EndPoint ep = (EndPoint)iep;
            sock.Bind(iep);

            while (Running)
            {

                data = new byte[1024];
                recv = sock.ReceiveFrom(data, ref ep);

                StringData = UnicodeEncoding.UTF8.GetString(data, 0, recv);

                Writing.WString.Message = StringData;
                box.Invoke(new MethodInvoker(BoxAccess));

                StringData = "";
            }
            sock.Close();
        }
        void BoxAccess()
        {
            writer.Parse(StringData, box);
        }
    }
}
